﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using PDFPARSERLib;
using Image=System.Drawing.Image;

namespace PdfLib
{
    /// <summary>
    /// 
    /// </summary>
    public class PdfImageReader
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="pageNum"></param>
        /// <returns></returns>
        public static Image GetPageImage(string filePath, int pageNum)
        {
            List<Image> imgs = new List<Image>();
            PDFPARSERLib.Document pdfDoc = new Document();
            try
            {
                if (pdfDoc.Open(filePath, string.Empty))
                {
                    pdfDoc.PageNo = pageNum;
                    PDFPARSERLib.Content pdfContent = pdfDoc.Page.Content;
                    if (pdfContent != null)
                    {
                        PDFPARSERLib.Image pdfImg;
                        pdfImg = pdfContent.GetNextImage();
                        int i = 0;

                        while (pdfImg != null)
                        {
                            i++;
                            string tiffFilePath = filePath + "_" + pageNum + "_" + i.ToString() + ".tif";
                            pdfImg.Store(tiffFilePath, TPDFCompression.eComprRaw);
                            Image img = Image.FromFile(tiffFilePath);
                            imgs.Add(img);
                            pdfImg = pdfContent.GetNextImage();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to extract image: " + ex.ToString());
            }
            finally
            {
                pdfDoc.Close();
            }

            if (imgs.Count == 1)
                return new Bitmap(imgs[0]);
            else
                return null;
        }

    }
}
